package com.test.base.config;

import com.alibaba.fastjson.JSONObject;
import com.test.base.api.AuthApi;
import com.test.base.utils.TokenUtil;
import com.test.base.vo.api.WxInfoResult;
import com.test.base.vo.common.ResultData;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class ApiLoginInterceptor implements HandlerInterceptor {
    private Logger logger = LoggerFactory.getLogger(ApiLoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String basePath = httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort();
        String requesturl = httpServletRequest.getRequestURL().toString();
        String[] exUrl = new String[]{"/api/index/index", "/api/auth/loginByWeixin"};
        boolean bool = false;
        for (String ex : exUrl) {
            if (requesturl.equals(basePath + ex)) {
                bool = true;
                break;
            } else {
                continue;
            }
        }
        if (bool) {
            return true;
        } else {
            String token = httpServletRequest.getHeader("X-Nideshop-Token");
            if (StringUtils.isEmpty(token)) {
                ResultData fail = ResultData.fail(401, "请先登录");
                returnJson(httpServletResponse, JSONObject.toJSONString(fail));
                return false;
            } else {
                WxInfoResult info = TokenUtil.pase(token);
                if (info.equals(null) || info.getUserId().equals(null) || info.getUserId() <= 0) {
                    ResultData fail = ResultData.fail(401, "请先登录");
                    returnJson(httpServletResponse, JSONObject.toJSONString(fail));
                    return false;
                } else {
                    httpServletRequest.setAttribute("userId",info.getUserId());
                    return true;
                }
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    private void returnJson(HttpServletResponse response, String json) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
            logger.error("response error", e);
        } finally {
            if (writer != null)
                writer.close();
        }
    }
}
